package com.gw.quotes.activity.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.gw.quotes.R;
import com.gw.quotes.activity.LoginActivity;
import com.gw.quotes.activity.QuoteProductDetailActivity;
import com.gw.quotes.adapter.QuoteAdapter;
import com.gw.quotes.entity.business.ProjectListEntity.ProjectItem;
import com.gw.quotes.net.BaseServiceInter;
import com.gw.quotes.net.HttpCallBack;
import com.gw.quotes.net.Request;
import com.gw.quotes.net.Response;
import com.gw.quotes.net.service.ProjectListQueryServiceImpl;
import com.gw.quotes.util.CommonTools;
import com.gw.quotes.util.DialogUtils;
import com.gw.quotes.util.DialogUtils.DialogCallBack;
import com.yxw.util.StringUtils;
import com.yxw.view.YXWXListView;
import com.yxw.view.YXWXListView.IXListViewListener;

public class QuoteFragment extends BaseMainFragment implements
		IXListViewListener {

	private View contextView = null;

	@ViewInject(id = R.id.quote_listView)
	private YXWXListView quote_listView;

	private String loginName = "";

	private ArrayList<ProjectItem> projectlist;
	private QuoteAdapter quoteAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (contextView == null) {
			contextView = inflater.inflate(R.layout.fragment_activity_quote,
					null);
		}
		ViewGroup parent = (ViewGroup) contextView.getParent();
		if (parent != null) {
			parent.removeView(contextView);
		}
		FinalActivity.initInjectedView(this, contextView);
		initView();
		return contextView;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (getLoginUser() == null) {
			DialogUtils.alertDialog("您尚未登录，请先登录！", mActivity,
					new DialogCallBack() {
						@Override
						public void onNegativeButton(Object o) {
							Intent intent = new Intent(context,
									LoginActivity.class);
							startActivity(intent);
						}
					});
		} else {
			if (!StringUtils.isEmpty(loginName)
					&& loginName != getLoginUser().getLoginname()) {
				// 重新加载
				if ((projectlist = (ArrayList<ProjectItem>) aCache
						.getAsObject("projectlist_"
								+ getLoginUser().getLoginname())) == null) {
					// 启动加载数据
					quote_listView.startRefresh();
					if (quoteAdapter != null) {
						quoteAdapter.clear();
					}
				} else {
					Date lastdate = aCache.getLastSaveTime("projectlist_"
							+ getLoginUser().getLoginname());
					quote_listView.setRefreshTime(lastdate == null ? "尚未更新"
							: DateFormat
									.format("yyyy-MM-dd hh:mm:ss", lastdate)
									.toString());
					quoteAdapter = new QuoteAdapter(contextView.getContext(),
							R.layout.item_quote, projectlist);
					quote_listView.setAdapter(quoteAdapter);
				}

			} else {
				// 首次加载
				if ((projectlist = (ArrayList<ProjectItem>) aCache
						.getAsObject("projectlist_"
								+ getLoginUser().getLoginname())) == null) {
					// 启动加载数据
					quote_listView.startRefresh();
				} else if (quoteAdapter == null) {
					Date lastdate = aCache.getLastSaveTime("projectlist_"
							+ getLoginUser().getLoginname());
					quote_listView.setRefreshTime(lastdate == null ? "尚未更新"
							: DateFormat
									.format("yyyy-MM-dd hh:mm:ss", lastdate)
									.toString());
					quoteAdapter = new QuoteAdapter(contextView.getContext(),
							R.layout.item_quote, projectlist);
					quote_listView.setAdapter(quoteAdapter);
				}
			}
			loginName = getLoginUser().getLoginname();
		}
	}

	private void initView() {
		// quote_listView.setPullLoadEnable(true);
		// quote_listView.setAdapter(mAdapter);
		quote_listView.setPullLoadEnable(false);
		// quote_listView.setPullRefreshEnable(false);
		quote_listView.setXListViewListener(this);
		quote_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (projectlist.get((int) id).getProjecttype() == 2) {
					Intent intent = new Intent(contextView.getContext(),
							QuoteProductDetailActivity.class);
					intent.putExtra("itemInfo", projectlist.get((int) id));
					startActivity(intent);
				} else {
					CommonTools.showShortToast(context, "“"
							+ QuoteAdapter.PROJCETTYPE[projectlist
									.get((int) id).getProjecttype() - 1]
							+ "”暂不支持详情显示");
				}

			}
		});
	}

	/**
	 * 发送请求获取列表信息
	 */
	private void requestList() {
		BaseServiceInter httpService = new ProjectListQueryServiceImpl();
		Request request = new Request();
		request.setLoginname(getLoginUser().getLoginname());
		request.setTicket(getLoginUser().getTicket());
		Response response = httpService.handler(request,
				new HttpCallBack<Response<ArrayList<ProjectItem>>>() {
					@Override
					public void onFinished(
							Response<ArrayList<ProjectItem>> response) {
						if (response != null) {
							// CommonTools.showShortToast(context,
							// "msg:"
							// + response.getMsg()
							// + "result:"
							// + response.getResult()
							// + "Buyerorgname:"
							// + response.getObj().get(0)
							// .getBuyerorgname());
							projectlist = response.getObj();
							aCache.put("projectlist_"
									+ getLoginUser().getLoginname(),
									projectlist);
							quoteAdapter = new QuoteAdapter(contextView
									.getContext(), R.layout.item_quote,
									projectlist);
							quote_listView.setAdapter(quoteAdapter);
						}
						onLoad();
					}
				});
	}

	private void onLoad() {
		quote_listView.stopRefresh();
		quote_listView.stopLoadMore();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		quote_listView.setRefreshTime(df.format(new Date()));
	}

	@Override
	public void onRefresh() {
		requestList();
	}

	@Override
	public void onLoadMore() {
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				onLoad();

			}
		}, 2000);
	}

}
